﻿using System;
using System.Collections.Generic;
using CompactMapper.Orm.Contracts;
using CompactMapper.Orm.Extensions;

namespace CompactMapper.Orm.UnitOfWork
{
    internal sealed class IdentityMap<T>
        where T : class, IKeyedPersistent
    {
        private readonly Dictionary<IKey, T> _identityMap;


        public IdentityMap()
        {
            _identityMap = new Dictionary<IKey, T>();
        }


        public T this[IKey key]
        {
            get
            {
                if (_identityMap.ContainsKey(key))
                {
                    return _identityMap[key];
                }
                throw new KeyNotFoundException(String.Format("key {0} not found", key));
            }
        }

        public Boolean Contains(IKey key)
        {
            return key.IsSet() && _identityMap.ContainsKey(key);
        }

        public void Add(T entity)
        {
            if (_identityMap.ContainsKey(entity.Key))
                return;
            _identityMap.Add(entity.Key, entity);
        }

        public void Remove(IKey key)
        {
            if (Contains(key))
            {
                _identityMap.Remove(key);
            }
        }

        public void Clear()
        {
            _identityMap.Clear();
        }
    }
}